<template>
  <section>
    <!--工具条：关键字查询 + 新增-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getPets">关键字</el-button>
        </el-form-item>
        <el-form-item>
          <!--v-perm="'menu:add'"-->
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>

        <el-form-item>
          <!--v-perm="'menu:add'"-->
          <el-button type="primary" @click="onShelves">上架</el-button>
        </el-form-item>

        <el-form-item>
          <!--v-perm="'menu:add'"-->
          <el-button type="primary" @click="offShelves">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表：优秀实践，copy domain修改列表-->
    <el-table :data="pets" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <!--      <el-table-column type="index" width="60">
            </el-table-column>-->
      <el-table-column prop="name" label="名称"  sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="成本" sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="市场价"  sortable>
      </el-table-column>
      <el-table-column prop="typeName" label="类型" sortable>
      </el-table-column>
      <!--      <el-table-column prop="resources" label="资源"  sortable>
            </el-table-column>-->
      <!--      <el-table-column prop="state" label="状态"  >
              <template slot-scope="scope">
                <span  v-if="scope.row.state=1" style="color: green">正常</span>
                <span v-else style="color: red">禁用</span>
              </template>
            </el-table-column>-->

      <el-table-column prop="state" label="状态">
        <template slot-scope="scope">
          <span v-if="scope.row.state==0" style="color: red">下架</span>
          <span v-else-if="scope.row.state==1" style="color: green">上架</span>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" sortable>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" sortable>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" sortable>
      </el-table-column>
      <el-table-column prop="shopName" label="所属店铺" sortable>
      </el-table-column>
      <el-table-column prop="userName" label="领养人" sortable>
      </el-table-column>

      <el-table-column label="操作" min-width="120">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <!-- v-perm="'menu:delete'" -->
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totals"
          style="float:right;">
      </el-pagination>
      <!--      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="currentPage"
                           :page-size="pageSize" :total="totals" style="float:right;">
            </el-pagination>-->
    </el-col>

    <!--新增和编辑对话框-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <!--ref="menuForm" 指定表单名称，以后可以通过this.$refs.menuForm-->
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item class="block" label="类型" prop="typeId" >
          <!--          <el-input v-model="saveForm.parentId" auto-complete="off"></el-input>-->
          <span class="demonstration"></span>
          <el-cascader v-model="saveForm.typeId"
                       :options="options"
                       :props="{
                checkStrictly: true,
                label: 'name',
                value: 'id',
                emitPath: true,

              }"
                       clearable></el-cascader>
        </el-form-item>

        <el-form-item label="所属店铺" prop="shopId">
          <!--          <el-input v-model="saveForm.managerId" auto-complete="off"></el-input>-->
          <template>
            <el-select v-model="saveForm.shopId" placeholder="请选择">
              <el-option
                  v-for="item in managers"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id">
                <span style="float: left">{{ item.name }}</span>
              </el-option>
            </el-select>
          </template>
        </el-form-item>

        <el-form-item label="资源" prop="resources">
          <!--<el-input v-model="editForm.resources" auto-complete="off"></el-input>-->
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor v-model="saveForm.intro"  :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor  v-model="saveForm.adoptNotice"  :options="quillOption">
          </quill-editor>
        </el-form-item>

<!--        <el-form-item label="简介" prop="intro">
          <quill-editor v-model="editForm.petdetail.intro" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="预约须知" prop="adoptNotice">
          <quill-editor v-model="editForm.petdetail.adoptNotice" :options="quillOption">
          </quill-editor>
        </el-form-item>-->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">保存</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import {quillEditor} from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from "../../common/js/quill-config";

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      quillOption: quillConfig,

      //分页显示所属数据
      pets: [],
      options: [],
      managers: [],
      listLoading: false,
      currentPage: 1,
      pageSize: 10,
      totals: 0,

      //高级查询所需数据
      keyword: '',
      //文件上传相关数据
      fileList: [],

      //多条数据选中
      sels: [],//列表选中列


      //添加或修改数据
      saveFormVisible: false,//添加或修改界面是否显示
      saveLoading: false,
      title: null,
      menuTree: [],
      saveFormRules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
        costprice: [
          {required: true, message: '请输入成本', trigger: 'blur'}
        ],
        saleprice: [
          {required: true, message: '请输入售价', trigger: 'blur'}
        ],
      },

      //编辑界面数据
      saveForm: {
        name: '',
        costprice: '',
        saleprice: '',
        resources: '',
        typeId: '',
        shopId: '',
        intro: '',
        adoptNotice: ''
      }
    }
  },
  methods: {
    //获取菜单列表
    getPets() {
      //开启加载框
      this.listLoading = true;
      let param = {
        "currentPage": this.currentPage,
        "pageSize": this.pageSize,
        "keyword": this.keyword
      };
      this.$http.post("/pet/selectByQueryPage", param).then(res => {
        let {success, resultObj} = res.data;
        if (success) {
          this.pets = resultObj.list;
          this.totals = resultObj.total;
        }
        //关闭加载框
        this.listLoading = false;
      })
    },

    //分页查询 - 点击某一页查询
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPets();
    },

    //点击排序
    handleChange(value) {
      this.saveForm.index = value;
    },

    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/pet/" + row.id).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            //计算总页数
            let totalPage = this.totals % this.pageSize == 0 ? this.totals / this.pageSize
                : Math.ceil(this.totals / this.pageSize);
            if (this.currentPage > 1 && this.currentPage == totalPage && (this.totals - 1) % this.pageSize == 0) {
              this.currentPage = this.currentPage - 1;
            }
            this.getPets();
          } else {
            this.$message.error("删除失败【500】");
          }
        }).catch(res => {
          this.$message.error("系统错误【400,404】");
        })
      }).catch(() => {
        //确认框点击取消之后走这里
      });
    },

    //点击修改按钮弹出模态框
    handleEdit: function (index, row) {
      this.title = "编辑";
      this.fileList=[];
      this.saveForm = Object.assign({}, row);
      console.log(this.saveForm);
      //将resources以,为间隔拆分成字符串
      let resourcesList = [];
      resourcesList = this.saveForm.resources.split(",");
      //遍历拆分后的数组，将每个元素赋值给fileList
      for (let i = 0; i < resourcesList.length; i++) {
        this.fileList.push({
          name: resourcesList[i],
          url: resourcesList[i]
        });
      }

      //对上级菜单回显做处理：//这里没有dirPath - 无法显示多级部门，只能显示上级部门
      //注意回显的时候：只能选顶级部门，
      /*this.saveForm.parent = [row.parentId];*/
      this.saveFormVisible = true;
      this.getManagers();
      this.getPetTypeTree();
    },

    //点击添加按钮弹出模态框
    handleAdd: function () {
      //修改对话框标题
      this.title = "新增"
      //置空数据，防止先点修改，后点添加有值
      this.fileList=[];
      this.saveForm = {
        name: '',
        costprice: '',
        saleprice: '',
        resources: '',
        typeId: '',
        shopId: '',
        intro: '',
        adoptNotice: ''
      };
      /*      this.getMenuTree();//加载父级菜单*/
      //弹出对话框
      this.saveFormVisible = true;
      this.getPetTypeTree();
      this.getManagers();
    },
/*
    //图片预览
    handlePreview(file) {
      console.log(file);
    },*/

    //文件删除的业务逻辑
    handleRemove(file, fileList) {
      // Object {response: Object { success: true, message: "操作成功", resultObj: "/group1/M00/00/0F/oYYBAGJ6JmyATaYbAAk1mWiyf0E903.gif" }}
      var filePath =file.response.resultObj;
      this.$http.delete("/fastDfs?path="+filePath).then(res=>{
        if(res.data.success){
          this.$message({
            message: '删除成功!',
            type: 'success'
          });
        }else{
          this.$message({
            message: '删除失败!',
            type: 'error'
          });
        }
      })
    },

    //文件上传的业务逻辑
    handleSuccess(response, file, fileList){
      //Object { success: true, message: "操作成功", resultObj: "/group1/M00/00/0F/oYYBAGJ6JV2ANENZAAhNlgqHjro238.gif" }
/*      console.log(response);*/
      //console.log(file);
      //console.log(fileList);
      this.saveForm.resources ="http://60.204.187.34:8800" + response.resultObj;
    },

    /*handleSuccess(response, file, fileList){
      //1.只要把action属性写对了就可以上传了
      //处理resources
      if(this.saveForm.resources){//有值
        this.saveForm.resources = this.saveForm.resources+","+ "http://60.204.187.34:8800" +response.resultObj;
      }else{
        this.saveForm.resources ="http://60.204.187.34:8800" + response.resultObj;
      }
      //处理fileList:resources = xx,xx,xx
      this.fileList=[];//先清空 - 再添加最新的所有该宠物图片
      if(this.saveForm.resources){
        let arr = this.saveForm.resources.split(",");//[xx,xx,xx]
        for(var i = 0;i<arr.length;i++){
          this.fileList.push({"url":"http://service-file-primary.java.itsource.cn"+arr[i]});
        }
      }
    },*/

    //点击模态框提交数据
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let paras = Object.assign({}, this.saveForm);

            //提交数据时上级部门数据格式做处理：[3,8] - {id:8}
            var arr = this.saveForm.typeId; //[ 3, 8 ]
            if (arr) {
              paras.typeId = arr[arr.length - 1]
            }
            /*if (this.saveForm.typeId!=null){
              //将数组parentId转为字符串
              this.saveForm.typeId = this.saveForm.typeId.join(",");
              //截取parentId中最后一个","后面的数赋值给parentId
              this.saveForm.typeId = this.saveForm.typeId.substring(this.saveForm.typeId.lastIndexOf(",") + 1);
            }*/

            this.$http.put("/pet/save", paras).then(res => {
              this.saveFormVisible = false;
              this.saveLoading = false;
              if (res.data.success) {
                this.getPets();
              } else {
                this.$message.error("操作失败【500】");
              }
            }).catch(res => {
              this.$message.error("系统错误【400,404】");
            })
          });
        }
      });
    },
    //选择每页显示记录条数
    handleSizeChange(curentPage) {
      this.pageSize = curentPage
      this.getPets();
    },

    selsChange: function (sels) {
      this.sels = sels;
    },

    getManagers() {
      this.$http.get("/shop/selectAll").then(res => {
        this.managers = res.data;

      })
    },

    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/pet/patchDelete", ids).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.currentPage = 1;
            this.getPets();
          } else {
            this.$message.error("批量删除失败【500】");
          }
        }).catch(res => {
          this.$message.error("系统错误【400,404】");
        })
      }).catch(() => {
      });
    },


    //批量上架
    onShelves: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/pet/onShelves", ids).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.currentPage = 1;
            this.getPets();
          } else {
            this.$message.error("批量上架失败【500】");
          }
        }).catch(res => {
          this.$message.error("系统错误【400,404】");
        })
      }).catch(() => {
      });
    },

    //批量下架
    offShelves: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认下架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/pet/offShelves", ids).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.currentPage = 1;
            this.getPets();
          } else {
            this.$message.error("批量下架失败【500】");
          }
        }).catch(res => {
          this.$message.error("系统错误【400,404】");
        })
      }).catch(() => {
      });
    },

    getPetTypeTree() {
      this.$http.get("/petType/getPetTypeTree").then(res => {
        this.options = res.data.resultObj;
      })
    },


  },
  mounted() {
    //分页查询 - 页面一加载查询
    this.getPets();
  }
}

</script>

<style scoped>

</style>